package com.wei.inteceprot;

import com.wei.blog.common.constants.UserConstants;
import com.wei.blog.common.help.UserHelp;
import com.wei.blog.common.utils.CookieUtils;
import com.wei.vo.UserToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
@Slf4j
public class LoginUserInterceprot implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserHelp userHelp;

    //controller前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie获取token
        String token = CookieUtils.getValue(request);
        /*校验token*/
        if (!ObjectUtils.isEmpty(token)) {
            UserToken userToken = (UserToken) redisTemplate.opsForValue().get(
                    String.format(UserConstants.USER_LOGIN_TOKEN, token)
            );
            /*判断userToken是否为空，以及是否过期*/
            if (userToken != null && userToken.getTtl().after(new Date())) {
                /*存放放在userHelp中*/
                userHelp.set(userToken);
            } else {
                log.debug("token过期或redis中不存在该token");
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserToken userToken = userHelp.get();
        if(userToken!=null){
            if (modelAndView!=null){
                modelAndView.addObject("loginUser",userToken);
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            userHelp.remove();
    }

}
